
import 'package:zfth/pages/home/homegrid/HomeGridState.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:zfth/utils/Settings.dart';
import '../../../api/ReportApi.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import '../../../utils/eventbus/EventBus.dart';
import '../../../utils/eventbus/EventBusMethod.dart';

class HomeGridLogic extends GetxController{

  final state = HomeGridState();


  @override
  void onInit() {
    queryNeedHandleAlarmCount();

    bus.on(EventBusMethod.methods["wbSocket事件"], (arg) {
      if(arg["type"] == Settings.websocketDataType["待处理的报警数量"]){
        state.handleCount = arg["data"];
        update();
      }
    });

    super.onInit();
  }


  @override
  void onClose() {
    bus.off(EventBusMethod.methods["wbSocket事件"]);
    super.onClose();
  }

  void queryNeedHandleAlarmCount() async{
    dynamic res =  await ReportApi.needHandleAlarm();
    if(res["success"]){
      state.handleCount = res["result"];
      update();
    }else{
      EasyLoading.showError("需要处理的报警数据查询失败");
    }
  }

  List<Widget> gridItem(){
    List<Widget> li = [];
    for(dynamic item in state.gridItemList){
      li.add(
          GestureDetector(
            child:Stack(
              alignment:Alignment.topCenter,
              children: [
                Column(
                  children: [
                    Image.asset("images/${item['icon']}",width: 45),
                    const SizedBox(height: 2,),
                    Text(item["title"],overflow: TextOverflow.ellipsis ,)
                  ],
                ),
                itemBadge(item)
              ],
            ),
            onTap:()=>{
              Get.toNamed(item["path"],)

            } ,
          )
      );
    }
    return li;
  }

  Widget itemBadge(item){
    if(item['badgeType']!=null && state.handleCount[item['badgeType']]!>0){
      return Positioned(
          top:0,
          right: 22,
          child: Container(
            alignment: Alignment.center,
            width: 16,
            height: 16,
            decoration: BoxDecoration(
              color: Colors.red,
              borderRadius: const BorderRadius.all(Radius.circular(8)),
              border: Border.all(width: 0, style: BorderStyle.none),
            ),
            child:Text("${state.handleCount[item['badgeType']]}",style: const TextStyle(color: Colors.white,fontSize: 10)),

          )
      );
    }else{
      return const SizedBox(height: 0,);
    }
  }
}